import { NextRequest, NextResponse } from 'next/server'
import { readFile } from 'fs/promises'
import path from 'path'
import { existsSync } from 'fs'

// 简单的 MIME 类型映射
const getMimeType = (filename: string): string => {
    const ext = path.extname(filename).toLowerCase()
    const mimeTypes: { [key: string]: string } = {
        '.jpg': 'image/jpeg',
        '.jpeg': 'image/jpeg',
        '.png': 'image/png',
        '.gif': 'image/gif',
        '.webp': 'image/webp',
        '.svg': 'image/svg+xml',
        '.pdf': 'application/pdf',
        '.txt': 'text/plain',
        '.json': 'application/json'
    }
    return mimeTypes[ext] || 'application/octet-stream'
}

export async function GET(
    request: NextRequest,
    { params }: { params: { userId: string; filename: string } }
) {
    try {
        const { userId, filename } = params
        
        // 安全检查：防止路径遍历攻击
        if (userId.includes('..') || filename.includes('..')) {
            return NextResponse.json({ error: '非法路径' }, { status: 400 })
        }
        
        // 构建文件路径
        const filePath = path.join(process.cwd(), 'uploads', 'users', userId, 'image', filename)
        
        // 检查文件是否存在
        if (!existsSync(filePath)) {
            return NextResponse.json({ error: '文件不存在' }, { status: 404 })
        }
        
        // 读取文件
        const fileBuffer = await readFile(filePath)
        
        // 获取文件的MIME类型
        const mimeType = getMimeType(filename)
        
        // 返回文件
        return new NextResponse(fileBuffer, {
            headers: {
                'Content-Type': mimeType,
                'Cache-Control': 'public, max-age=31536000, immutable',
            },
        })
        
    } catch (error) {
        console.error('文件访问错误:', error)
        return NextResponse.json(
            { error: '文件访问失败' },
            { status: 500 }
        )
    }
}